package com.example.guidedanimationdemo;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.RelativeLayout; 
import java.util.ArrayList;
import java.util.List;

/**
 * 向上滑动、双击 引导页 -- 个人中心
 * Created by xuqunxing on 2017/8/3.
 */
public class VideoDetailGuideView3 extends RelativeLayout {
    private Paint mPaint;
    private Paint mPaintChange;
    private Bitmap targetBitmap;//手指滑动下面的线
    private Bitmap handBitmap;
    private Bitmap textBitmap;
    public static int GUIDE_SHOW_TYPE_DEFAULT = 0;//向上滑动
    public static int GUIDE_SHOW_TYPE_DOUBLE = 1;//双击引导
    private int type = GUIDE_SHOW_TYPE_DEFAULT;
    private boolean doDraw = false;//是否执行画布
    private boolean radiusAdd = true;
    private boolean radiusBigAdd = true;
    private int radiusMax = 0;
    private int alphaInt = 255;
    private int alphaIntBig = 255;
    private boolean alphaIntAdd = false;
    private boolean alphaIntBigAdd = false;
    private int radiusBigMax = 0;
    private int handX;
    private int handY;//一开始显示的位置高度
    private int targetX;
    private int targetY;//手指的高度+4dp
    private int radius;
    private int radiusBig;
    private int radiusBigMin;
    private int circleInnerXX;
    private int circleInnerYY;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (radiusAdd) {//小圆
                        radius = radius + 2;
                    } else {
                        radius = radius - 2;
                    }

                    if (radius >= radiusMax) {
                        radiusAdd = false;
                    } else if (radius <= textBitmap.getWidth() / 2) {
                        radiusAdd = true;
                    }

                    if (radiusBigAdd) {//大圆
                        radiusBig = radiusBig + 2;
                    } else {
                        radiusBig = radiusBig - 2;
                    }

                    if (radiusBig >= radiusBigMax) {
                        radiusBigAdd = false;
                    } else if (radiusBig <= radiusBigMin) {
                        radiusBigAdd = true;
                    }

                    if (!alphaIntAdd) {
                        alphaInt = alphaInt - 13;
                    } else {
                        alphaInt = alphaInt + 13;
                    }

                    if (alphaInt <= 0) {
                        alphaInt = 0;
                        alphaIntAdd = true;
                    } else if (alphaInt >= 255) {
                        alphaInt = 255;
                        alphaIntAdd = false;
                    }
                    //-----------
                    if (!alphaIntBigAdd) {
                        alphaIntBig = alphaIntBig - 10;
                    } else {
                        alphaIntBig = alphaIntBig + 10;
                    }

                    if (alphaIntBig <= 0) {
                        alphaIntBig = 0;
                        alphaIntBigAdd = true;
                    } else if (alphaIntBig >= 255) {
                        alphaIntBig = 255;
                        alphaIntBigAdd = false;
                    }
                    Log.e("======", "======alpha444:" + alphaIntBig);
                    invalidate();
                    break;
            }
        }
    };

    public VideoDetailGuideView3(Context context) {
        this(context, null);
    }

    public VideoDetailGuideView3(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoDetailGuideView3(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackgroundColor(Color.TRANSPARENT);//要绘制一个透明的，要不然不调用onDraw
        if (mPaint == null) {
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaintChange = new Paint();
            mPaintChange.setAntiAlias(true);
        }
        mPaint.setColor(Color.parseColor("#b2000000"));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        setVisibility(GONE);
//        doDraw = false;
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (doDraw) {
            if (type == GUIDE_SHOW_TYPE_DEFAULT) {
                if (textBitmap == null) {
                    textBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_text))).getBitmap();
                }
                if (targetBitmap == null) {
                    targetBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_target2))).getBitmap();
                }
                if (handBitmap == null) {
                    handBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_hand2))).getBitmap();
                }
                //SRC_OVER:上下层都显示,运算后上层在上面，假如两张图都是半透明的，这种模式无论谁上谁下，两者都看得到，达不到理想的只显示一个
                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
                canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), mPaint);
                if (handAniYY == 0) {
                    drawTextBitmap(canvas);
                    handX = ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - handBitmap.getWidth() / 3;
                    handY = ScreenUtil.getCurrentScreenHeight(getContext()) / 2 - handBitmap.getHeight();
                    Log.e("======", "======000handx:" + handX + "---handY:" + handY + "--currentValue:" + currentValue);
                    drawHandBitmap(canvas);

                    targetX = handX + ScreenUtil.dip2px(getContext(),4);//ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - handBitmap.getWidth() / 3 - targetBitmap.getWidth() / 2;
                    targetY = handY + ScreenUtil.dip2px(getContext(),4);//ScreenUtil.getCurrentScreenHeight(getContext()) / 2 - handBitmap.getHeight() - targetBitmap.getHeight() / 2;

                    drawTargetBitmap(canvas);
                    //  canvas.save();
                    startHandAnim();
                } else {
                    // canvas.restore();
                    drawTextBitmap(canvas);
                    drawHandBitmap(canvas);
                    drawTargetBitmap(canvas);
                }
            } else if (type == GUIDE_SHOW_TYPE_DOUBLE) {
                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
                canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), mPaint);
                if (textBitmap == null) {
                    textBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_double_text))).getBitmap();
                    radius = textBitmap.getWidth() / 2;
                    radiusBig = textBitmap.getWidth() / 2 + ScreenUtil.dip2px(getContext(), 7);
                    radiusBigMin = radiusBig;
                    radiusMax = radius + ScreenUtil.dip2px(getContext(), 7);
                    radiusBigMax = radiusBig + ScreenUtil.dip2px(getContext(), 7);
                }

                circleInnerXX = ScreenUtil.getCurrentScreenWidth(getContext()) / 2;
                circleInnerYY = ScreenUtil.getCurrentScreenHeight(getContext()) / 2;
                drawTextBitmap(canvas);

                canvas.drawCircle(circleInnerXX, circleInnerYY - (radiusBigMax), radiusBig, initPaintBig(alphaInt));
                canvas.drawCircle(circleInnerXX, circleInnerYY - (radiusBigMax), radius, initPaint(alphaInt));
                if (alphaInt <= 0) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessageDelayed(message, 800);
                } else {
                    handler.sendEmptyMessage(0);
                }
            }
        }
    }

    private Paint initPaint(int alpha) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        // 设置是环形方式绘制
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setAlpha(alpha);
        Log.e("======", "======alpha2222:" + alpha);
        return paint;
    }

    private Paint initPaintBig(int alpha) {
        /*
         * 新建一个画笔
         */
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        // 设置是环形方式绘制
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getContext().getResources().getColor(R.color.white));
        paint.setAlpha(alpha);
        Log.e("======", "======alpha111:" + alpha);
        return paint;
    }

    private void drawHandBitmap(Canvas canvas) {
        try {
            mPaintChange.setAlpha((int) (currentValue * 255));
            canvas.drawBitmap(handBitmap,
                    handX,
                    handAniYY == 0 ? handY : handAniYY, mPaintChange);
            //Log.e("======","======111handx:"+handX+"---handY:"+handAniYY+"--currentValue:"+currentValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void drawTargetBitmap(Canvas canvas) {
        try {
            mPaintChange.setAlpha((int) (currentValue * 255));

            int height = (int) (handY  - handAniYY);
            int top = (targetY) - (height);
            Rect rectSrc = new Rect();
            rectSrc.left = targetX;
           // rectSrc.top = 200;
            rectSrc.bottom = targetY;
            rectSrc.right = targetX + targetBitmap.getWidth();

            Rect rectDst = new Rect();
            rectDst.left = targetX;
            rectDst.top = top;
            rectDst.bottom = targetY;
            rectDst.right = targetX + targetBitmap.getWidth();

            canvas.drawBitmap(targetBitmap,rectSrc,rectDst,mPaintChange);
            Log.e("======","======top:"+top+"---targetY:"+targetY + " -- heigh:"+height);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void drawTextBitmap(Canvas canvas) {
        try {
            canvas.drawBitmap(textBitmap,
                    ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - textBitmap.getWidth() / 2,
                    ScreenUtil.getCurrentScreenHeight(getContext()) / 2 + textBitmap.getHeight() + ScreenUtil.dip2px(getContext(), 10), mPaint);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private float handAniYY = 0;//随着滑动而逐渐改变的高度
    private float currentValue = 1.0f;
    AnimatorSet set;

    public void startHandAnim() {
        try {
            set = new AnimatorSet();
            ObjectAnimator gethandTranYAnim = gethandTranYAnim();
            ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(handBitmap, "alpha", 1f, 0f);
            alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    currentValue = (float) valueAnimator.getAnimatedValue();
                    //Log.e("======","======currentValue:"+currentValue);
                    invalidate();
                }
            });
            gethandTranYAnim.setRepeatCount(ValueAnimator.INFINITE);
            gethandTranYAnim.setRepeatMode(ValueAnimator.INFINITE);

            alphaAnimator.setRepeatCount(ValueAnimator.INFINITE);
            alphaAnimator.setRepeatMode(ValueAnimator.INFINITE);
            List<Animator> animators = new ArrayList<>();
            animators.add(gethandTranYAnim);
            animators.add(alphaAnimator);
            set.playTogether(animators);
            set.setDuration(1500);
            set.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ObjectAnimator gethandTranYAnim() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(handBitmap, "translationY", handY, handY - 500);
    //     Log.e("======","======handAniYY:"+handY+"--handY22:"+ (handY - 300));
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                handAniYY = (float) animation.getAnimatedValue();
            }
        });
        return anim;
    }

    public void setType(int type) {
        this.type = type;
        if (type == GUIDE_SHOW_TYPE_DOUBLE) {
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    setVisibility(GONE);
//                }
//            },5000);
        }
        invalidate();
    }

    public void setDoDraw(boolean doDraw) {
        this.doDraw = doDraw;
        if (!doDraw && set != null) {
            set.cancel();
        }
    }

}